package com.ds.command.task;

import com.ds.command.Command;
import com.ds.common.ConfigCode;
import com.ds.context.JDSActionContext;
import com.ds.context.JDSContext;
import com.ds.context.RunableActionContextImpl;
import com.ds.engine.JDSSessionHandle;
import com.ds.home.client.CommandClient;
import com.ds.home.ct.CtMsgDataEngine;
import com.ds.server.JDSClientService;
import com.ds.server.JDSServer;
import com.ds.server.context.MinServerActionContextImpl;

import java.util.concurrent.Callable;

public class AddSersorCommandTask implements Callable<Command> {

    private String serialno;

    private ConfigCode configCode;

    private MinServerActionContextImpl autoruncontext;

    private String gatewayieee;

    public AddSersorCommandTask(String gatewayieee, String serialno, String systemCode) {
        this.serialno = serialno;
        this.gatewayieee = gatewayieee;
        JDSContext context = JDSActionContext.getActionContext();
        this.autoruncontext = new MinServerActionContextImpl(context.getHttpRequest(), context.getOgnlContext());
        autoruncontext.setParamMap(context.getContext());
        this.configCode=autoruncontext.getConfigCode();
        if (context.getSessionId() != null) {
            autoruncontext.setSessionId(context.getSessionId());
            autoruncontext.getSession().put("sessionHandle", context.getSession().get("sessionHandle"));
        }
        autoruncontext.setSessionMap(context.getSession());
    }

    public Command call() throws Exception {
        JDSActionContext.setContext(autoruncontext);

        CtMsgDataEngine msgEngine = CtMsgDataEngine.getEngine(configCode);
        JDSSessionHandle handle = (JDSSessionHandle) autoruncontext.getSession().get("sessionHandle");
        JDSActionContext.setContext(new RunableActionContextImpl());

        JDSActionContext.getActionContext().getContext().put(JDSContext.SYSCODE, configCode);
        JDSClientService client = JDSServer.getInstance().getJDSClientService(handle, configCode);

        CommandClient commandClient = msgEngine.getCommandClientByieee(gatewayieee);
        Command msg = commandClient.sendAddSensorCommand(serialno, null).get();

        return msg;

    }

}
